package com.ncmem.up6.sql;

import org.apache.commons.lang.StringUtils;
import sun.swing.StringUIClientPropertyKey;

import java.lang.reflect.Array;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SqlSeter {

    /// <summary>
    /// 字段列表，默认判断操作=,a=@a
    /// </summary>
    List<SqlParam> m_params;
    /**
     * SQL更新字段
     * name=name2
     */
    List<String> m_sqls;

    public SqlSeter() {
        this.m_params = new ArrayList<SqlParam>();
        this.m_sqls = new ArrayList<String>();
    }

    public static SqlSeter build() { return new SqlSeter(); }
    public int size(){return this.m_params.size();}

    public SqlSeter set(String name,String value) {
        this.m_params.add(new SqlParam(name, value));
        return this;
    }
    public SqlSeter set(String name, int value)
    {
        this.m_params.add(new SqlParam(name, value));
        return this;
    }
    public SqlSeter set(String name, long value)
    {
        this.m_params.add(new SqlParam(name, value));
        return this;
    }
    public SqlSeter set(String name, Boolean value)
    {
        this.m_params.add(new SqlParam(name, value));
        return this;
    }
    public SqlSeter sql(String s){
        this.m_sqls.add(s);
        return this;
    }

    public SqlParam[] toArray() { return this.m_params.toArray(new SqlParam[this.m_params.size()]); }
    public void bind(SqlTable table, PreparedStatement cmd) throws SQLException, ParseException {
        SqlParam[] ps = table.mergeVal(this.toArray());
        for(int i = 0 ; i < ps.length;++i)
        {
            ps[i].bind(cmd,i+1);
        }
    }

    /**
     * a=?,nameLoc=nameSvr
     * @return
     */
    public String toSql(){
        List<String> names = new ArrayList<String>();
        //添加变量
        for (int i = 0 ; i < this.m_params.size();++i)
        {
            names.add( this.m_params.get(i).m_name+"=?");
        }
        //添加SQL
        for (int i = 0 ; i < this.m_sqls.size();++i)
        {
            names.add(this.m_sqls.get(i));
        }
        return StringUtils.join(names,",");
    }
}
